import redis.clients.jedis.Jedis;
import java.util.ArrayList;
import java.util.Scanner;
class Inventory {
	String productId;
	String productName;
	double price;
	int stock;
	public Inventory(String productId, String productName, double price, int stock) {
		this.productId = productId;
		this.productName = productName;
		this.price = price;
		this.stock = stock;
	}
}
public class InventorySystemDemo {
	public static void main(String[] args) {
		ArrayList<Inventory> inventoryList = new ArrayList<>();
		inventoryList.add(new Inventory("1", "iPhone 12", 7999.00, 100));
		inventoryList.add(new Inventory("2", "iPhone 12 Pro", 9999.00, 100));
		inventoryList.add(new Inventory("3", "iPhone 12 Pro Max", 10999.00, 100));
		inventoryList.add(new Inventory("4", "iPhone 12 mini", 6999.00, 100));
		inventoryList.add(new Inventory("5", "iPhone SE", 3299.00, 100));
		inventoryList.add(new Inventory("6", "iPhone 11", 5499.00, 100));
		inventoryList.add(new Inventory("7", "iPhone 11 Pro", 8499.00, 100));
		// 连接到本地的 Redis 服务
		Jedis jedis = new Jedis("127.0.0.1", 6379, 100000);
		// 写入货物信息到 Redis
		for (Inventory inventory : inventoryList) {
			String productKey = "product:" + inventory.productId;
			jedis.hset(productKey, "name", inventory.productName);
			jedis.hset(productKey, "price", String.valueOf(inventory.price));
			jedis.hset(productKey, "stock", String.valueOf(inventory.stock));
		}
		// 用于从控制台接收输入的扫描器对象
		Scanner scanner = new Scanner(System.in);
		// 提示用户输入产品ID，并接收输入
		System.out.println("请输入产品ID:");
		String productId = scanner.nextLine();
		// 关闭扫描器
		// 从 Redis 中读取产品信息
		String productKey = "product:" + productId;
		// 检查是否命中缓存
		if (!jedis.exists(productKey)) {
			// 如果没有命中缓存，则添加一条新的缓存记录
			System.out.println("Cache miss, adding to cache...");
			System.out.println("Please enter product name:");
			String productName = scanner.nextLine();
			System.out.println("Please enter product price:");
			double price = scanner.nextDouble();
			System.out.println("Please enter product stock:");
			int stock = scanner.nextInt();
			scanner.close();
			jedis.hset(productKey, "name", productName);
			jedis.hset(productKey, "price", String.valueOf(price));
			jedis.hset(productKey, "stock", String.valueOf(stock));
			System.out.println("Product added to cache!");
			System.out.println("Product name: " + productName);
			System.out.println("Product price: " + price);
			System.out.println("Product stock: " + stock);
		} else {
			System.out.println("Cache hit!");
			System.out.println("Product name: " + jedis.hget(productKey, "name"));
			System.out.println("Product price: " + jedis.hget(productKey, "price"));
			System.out.println("Product stock: " + jedis.hget(productKey, "stock"));
		}
		// 关闭连接
		scanner.close();
		jedis.close();
	}
}